/*
 * Copyright 2016 jeasonlzy(廖子尧)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.aierjun.ani.net.OkGo.okupload;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aierjun.ani.R;
import com.aierjun.ani.net.OkGo.NumberProgressBar;
import com.aierjun.ani.net.OkGo.UploadUtils;
import com.aierjun.ani.utils.BitmapUtils;
import com.aierjun.ani.utils.MPermission;
import com.aierjun.ani.utils.ToastUtil;
import com.aierjun.ani.widget.MyListView;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkUpload;
import com.lzy.okserver.task.XExecutor;
import com.lzy.okserver.upload.UploadListener;
import com.lzy.okserver.upload.UploadTask;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class UploadingActivity extends Activity implements XExecutor.OnAllTaskEndListener {
    private Float fraction = 0.0f;
    private TextView uploadDo, uploadOk;
    private FrameLayout upload_fragment_do, upload_fragment_ok;
    private MyListView recyclerView_do, recyclerView_ok;

    private OkUpload okUpload;
    private UploadAdapter adapter;

    private UpLoadDBHelper upLoadDBHelper;
    private UploadOverAdapter uploadOverAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uploadall_okgo);
        MPermission.with(this)
                .setPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .requestPermission();
        init();
        initView();
        addData(showOverData(localData()));
    }

    private void init() {
        okUpload = OkUpload.getInstance();
        okUpload.getThreadPool().setCorePoolSize(1);
        okUpload.addOnAllTaskEndListener(this);
        upLoadDBHelper = new UpLoadDBHelper(this, 1);
    }

    @MPermission.PermissionOK
    private void valdateSuccess() {
        Log.i("Ani", "权限通过");
    }

    @MPermission.PermissionFail
    public void validateFail() {
        Log.i("Ani", "上传 没有相应的权限");
    }

    //初始化View
    private void initView() {
        recyclerView_do = (MyListView) findViewById(R.id.recyclerView_do);
        recyclerView_ok = (MyListView) findViewById(R.id.recyclerView_ok);
        uploadDo = (TextView) findViewById(R.id.upload_do);
        uploadOk = (TextView) findViewById(R.id.upload_ok);
        upload_fragment_do = (FrameLayout) findViewById(R.id.upload_fragment_do);
        upload_fragment_ok = (FrameLayout) findViewById(R.id.upload_fragment_ok);

        uploadDo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upload_fragment_do.setVisibility(View.VISIBLE);
                upload_fragment_ok.setVisibility(View.GONE);
            }
        });
        uploadOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upload_fragment_do.setVisibility(View.GONE);
                upload_fragment_ok.setVisibility(View.VISIBLE);
            }
        });
    }

    //已完成数据
    private List<UploadEntity> localData() {
        List<UploadEntity> lists = new ArrayList<>();
        lists.clear();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //不对图进行压缩
        options.inSampleSize = 1;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        List<List> ss = upLoadDBHelper.query();
        if (ss != null)
            for (int i = 0; i < ss.size(); i++) {
                List s = ss.get(i);
                UploadEntity uploadEntity = new UploadEntity();
                uploadEntity.setName(s.get(1) + "");
                uploadEntity.setTag(s.get(2) + "");
                uploadEntity.setStatus(Integer.valueOf(s.get(3) + ""));
                uploadEntity.setFile(s.get(4) + "");
                uploadEntity.setBitmap(BitmapUtils.getImage((byte[]) s.get(5), options));
                lists.add(uploadEntity);
            }
        return lists;
    }

    //显示已完成数据
    private List<UploadEntity> listOver;

    private List<UploadEntity> showOverData(List<UploadEntity> lists) {
        uploadOverAdapter = new UploadOverAdapter(this, new UploadBtnClickListenter() {
            @Override
            public void onClick(View view, String tag, String btnName) {
                listOver = uploadOverAdapter.removeData(tag);
                upLoadDBHelper.delete(tag);
            }
        });
        uploadOverAdapter.setDatas(lists);
        recyclerView_ok.setAdapter(uploadOverAdapter);
        return listOver;
    }

    //上传中数据
    private UploadEntity addData(List<UploadEntity> list) {
        Intent intent = getIntent();
        String url = intent.getStringExtra("URL");
        HttpHeaders httpHeaders = (HttpHeaders) intent.getSerializableExtra("HttpHeaders");
        HttpParams httpParams = (HttpParams) intent.getSerializableExtra("HttpParams");
        int priority = intent.getIntExtra("Priority", 0);
        String tag = intent.getStringExtra("Tag");
        String file = intent.getStringExtra("File");

        if (url == null || url.equals(""))
            return null;
        if (tag == null || tag.equals(""))
            tag = System.currentTimeMillis() + "";

        if (list != null)
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getTag().equals(tag)) {
                    ToastUtil.showShort(this, "任务已存在！");
                    return null;
                }
            }
        UploadEntity uploadEntity = new UploadEntity();
        uploadEntity.setTag(tag);
        uploadEntity.setFile(file);
        uploadEntity.setBitmap(BitmapUtils.getLoacalBitmap(file));
        uploadEntity.setStatus(2);
        uploadEntity.setName(new File(file).getName());
        List<UploadEntity> listUpLoad = new ArrayList<>();//目前只支持一个
        listUpLoad.add(uploadEntity);
        showUpLoadData(listUpLoad);
        upLoadData(url, httpHeaders, httpParams, tag, priority, uploadEntity);
        return uploadEntity;
    }

    //显示上传中数据
    private List<UploadEntity> listUpLoad;

    private List<UploadEntity> showUpLoadData(List<UploadEntity> list) {
        adapter = new UploadAdapter(this, new UploadBtnClickListenter() {
            @Override
            public void onClick(View view, String tag, String btnName) {
                if (btnName.equals("REMOVE")) {
                    listUpLoad = adapter.removeData(tag);
                    upLoadDBHelper.delete(tag);
                } else if (btnName.equals("RESTART")) {

                }
            }
        });
        adapter.setDatas(list);
        recyclerView_do.setAdapter(adapter);
        return listUpLoad;
    }


    //上传任务
    private void upLoadData(final String url, HttpHeaders httpHeaders, HttpParams httpParams, String tag, int priority, final UploadEntity uploadEntity) {
        UploadTask<String> task = UploadUtils.upload(url, httpHeaders, httpParams, tag, priority, new UploadListener<String>(tag) {
            @Override
            public void onStart(Progress progress) {

            }

            @Override
            public void onProgress(Progress progress) {
                Log.d("Ani onProgress", "总大小 " + (float) progress.totalSize / 1024 / 1024 + "M    速度  " + (float) progress.speed / 1024 / 1024 + " KB/s   当前大小  " + (float) progress.currentSize / 1024 / 1024 + "M   状态  " + progress.status + "  进度 " + (int) ((fraction / (float) progress.totalSize) * 100));
                setProgressBar((int) ((fraction / (float) progress.totalSize) * 100));
                uploadEntity.setStatus(progress.status);
            }

            @Override
            public void onError(Progress progress) {

            }

            @Override
            public void onFinish(String s, Progress progress) {
                Log.d("Ani", progress.date + "" + progress.toString());
                setProgressBar(100);
                uploadEntity.setStatus(progress.status);
                upLoadDBHelper.insert(uploadEntity.getName(), uploadEntity.getTag(), uploadEntity.getStatus() + "", uploadEntity.getFile(), upLoadDBHelper.img(BitmapUtils.getLoacalBitmap(uploadEntity.getFile())));
                listUpLoad = adapter.removeData(uploadEntity.getTag());
                listOver = uploadOverAdapter.addData(uploadEntity);
            }

            @Override
            public void onRemove(Progress progress) {

            }

        });
        task.start();
    }

    public View getViewByPosition(int pos, ListView listView) {
        final int firstListItemPosition = listView.getFirstVisiblePosition();
        final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

        if (pos < firstListItemPosition || pos > lastListItemPosition) {
            return listView.getAdapter().getView(pos, null, listView);
        } else {
            final int childIndex = pos - firstListItemPosition;
            return listView.getChildAt(childIndex);
        }
    }

    //商城进度
    public void setProgressBar(int progress) {
        LinearLayout linearLayout = (LinearLayout) getViewByPosition(0, recyclerView_do);
        LinearLayout l = (LinearLayout) linearLayout.getChildAt(1);
        RelativeLayout relativeLayout = (RelativeLayout) l.getChildAt(1);
        TextView textView = (TextView) relativeLayout.getChildAt(0);
        textView.setText(progress + " / 100");
        NumberProgressBar numberProgressBar = (NumberProgressBar) l.getChildAt(2);
        numberProgressBar.setProgress(progress);
    }


    protected void onDestroy() {
        super.onDestroy();
        okUpload.removeOnAllTaskEndListener(this);
    }

    @Override
    public void onAllTaskEnd() {
        ToastUtil.showShort(this, "所有上传任务已结束");
    }


}

